/**
 * @author Eduardo Leonne Souza de Oliveira
 * @version 1.0
 * Date: 2011-12-29
 * Last change: 2011-12-29 
 * 
 */

package com.leonne.harpacristabrasileira.activities;

import java.util.ArrayList;

import android.content.Context;
import android.content.Intent;
import android.content.res.AssetFileDescriptor;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnBufferingUpdateListener;
import android.media.MediaPlayer.OnCompletionListener;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.GestureDetector;
import android.view.GestureDetector.OnGestureListener;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnKeyListener;
import android.view.View.OnTouchListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.TextView;

import com.leonne.harpacristabrasileira.R;
import com.leonne.harpacristabrasileira.dao.AnthemsDAO;
import com.leonne.harpacristabrasileira.lists.adapters.AnthemsAdapter;
import com.leonne.harpacristabrasileira.lists.vo.AnthemVO;
import com.leonne.harpacristabrasileira.tools.CustomWaitDialog;
import com.leonne.harpacristabrasileira.tools.DataCache;
import com.leonne.harpacristabrasileira.tools.InternetConnection;
import com.leonne.harpacristabrasileira.tools.MyConstants;
import com.leonne.harpacristabrasileira.tools.Utils;

public class FirstPageActivity extends GenericActivity implements
		OnGestureListener, OnCompletionListener, OnBufferingUpdateListener {

	private RelativeLayout player;
	private EditText edtSearch;
	private ListView lvAnthems;
	private ImageView imgPlayPayse;
	private ImageView imgStop;
	private SeekBar skBar;
	private TextView audioDuration;
	private TextView audioActualDuration;
	private TextView playerTitle;
	private AnthemsAdapter lvAnthemsAdapter;
	private ArrayList<AnthemVO> arrayAnthems;
	private AnthemsDAO dao;
	private GestureDetector gestureScanner;
	private float xDown;
	private float yDown;
	private boolean forceSearch = false;
	private int audioDurationMilliseconds;
	private int audioActualDurationMilliseconds = 0;
	private final Handler handler = new Handler();
	private boolean theDamnUpdateSeekBarThreadIsRunning = false;

	/**
	 * (non-Javadoc)
	 * 
	 * @see android.app.Activity#onCreate(android.os.Bundle)
	 */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		if (Utils.isWideScreen(this.getBaseContext()))
        	setContentView(R.layout.first_page_wide);
        else
        	setContentView(R.layout.first_page);

		this.gestureScanner = new GestureDetector(this);
		this.idAnthem = -1;
		this.player = (RelativeLayout) findViewById(R.id.firstPagePlayerLayout);
		this.edtSearch = (EditText) findViewById(R.id.edtSearch);
		this.lvAnthems = (ListView) findViewById(R.id.lvAnthems);
		this.imgPlayPayse = (ImageView) findViewById(R.id.firstPageImgPlayPlayer);
		this.imgStop = (ImageView) findViewById(R.id.firstPageImgStopPlayer);
		this.skBar = (SeekBar) findViewById(R.id.playerSeekBar);
		this.audioDuration = (TextView) findViewById(R.id.playerDuration);
		this.audioActualDuration = (TextView) findViewById(R.id.playerActualDuration);
		this.playerTitle = (TextView) findViewById(R.id.firstPageTitlePlayer);
		
		this.playerTitle.setSelected(true);
		
		this.dao = new AnthemsDAO(this.getBaseContext());
		Bundle extras = this.getIntent().getExtras();
		this.forceSearch = extras.getBoolean("FORCESEARCH");

		this.imgPlayPayse.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				playerPlayPause();
			}
		});
		
		this.imgStop.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				playerStop();
			}
		});

		this.lvAnthems.setOnItemClickListener(new OnItemClickListener() {
			public void onItemClick(AdapterView<?> av, View view, int position,
					long id) {
				lvAnthemsAdapter.setSelectedPos(position);
				Intent intent = new Intent(FirstPageActivity.this, TextContentPageActivity.class);
				TextView t = (TextView) view.findViewById(R.id.itemNumberAnthemsList);
				intent.putExtra("IDANTHEM", Integer.parseInt(t.getText().toString()));
				startActivity(intent);
				overridePendingTransition(R.anim.push_up_in, R.anim.push_up_out);
			}
		});

		this.lvAnthems.setOnTouchListener(new OnTouchListener() {
			public boolean onTouch(View v, MotionEvent event) {
				switch (event.getAction() & MotionEvent.ACTION_MASK) {
					case MotionEvent.ACTION_UP:
						float newX = event.getX();
						float newY = event.getY();
						float difX = xDown - newX;
						if (difX < 0)
							difX = difX * -1;
						float difY = yDown - newY;
						if (difY < 0)
							difY = difY * -1;
						if (difX > difY)
							return gestureScanner.onTouchEvent(event);
						else
							return false;
					case MotionEvent.ACTION_DOWN:
						xDown = event.getX();
						yDown = event.getY();
						return false;
				}
				return gestureScanner.onTouchEvent(event);
			}
		});

		this.edtSearch.setOnKeyListener(new OnKeyListener() {
			public boolean onKey(View v, int keyCode, KeyEvent event) {
				if (event.getAction() == KeyEvent.ACTION_DOWN
						&& keyCode == KeyEvent.KEYCODE_ENTER) {
					forceSearch = true;
					MyConstants.ISFAVORITE = false;
					InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
					imm.hideSoftInputFromWindow(edtSearch.getWindowToken(), 0);
					CustomWaitDialog cwd = new CustomWaitDialog(FirstPageActivity.this, "updateData", "updateListView", true);
					cwd.execute();
				}
				return false;
			}
		});
		registerForContextMenu(this.lvAnthems);
		this.initiateMediaPlayer();
		CustomWaitDialog cwd = new CustomWaitDialog(FirstPageActivity.this, "updateData", "updateListView", true);
		cwd.execute();
	}
	

	public void initiateMediaPlayer() {
		initiateGeneralMediaPlayer();
		
		if (this.generalMediaPlayer.isPlaying()){
			int duration = ((int) (this.generalMediaPlayer.getDuration() / 1000)) * 1000;
			int milliseconds = ((int) (this.generalMediaPlayer.getCurrentPosition() / 1000)) * 1000;
			this.skBar.setMax(duration);
			this.audioDurationMilliseconds = duration;
			this.audioActualDurationMilliseconds = milliseconds;
			this.audioActualDuration.setText(Utils.formatMiliseconds(milliseconds));
			this.audioDuration.setText(Utils.formatMiliseconds(duration));
			this.playerTitle.setText(String.valueOf(MyConstants.idAnthemIsPlaying)+ ". " + MyConstants.titleAnthemIsPlaying);
			this.player.setVisibility(View.VISIBLE);
			if (!this.theDamnUpdateSeekBarThreadIsRunning)
				updateSeekBar();
		}
		this.skBar.setOnTouchListener(new OnTouchListener() {
			public boolean onTouch(View v, MotionEvent event) {
				switch (event.getAction()) {
				case MotionEvent.ACTION_DOWN:
					if (generalMediaPlayer.isPlaying()) {
						generalMediaPlayer.pause();
					}
					break;
				case MotionEvent.ACTION_UP:
					if (v.getId() == R.id.playerSeekBar) {
						SeekBar s = (SeekBar) v;
						int milisseconds = ((int) (s.getProgress() / 1000)) * 1000;
						audioActualDurationMilliseconds = milisseconds;
						audioActualDuration.setText(Utils.formatMiliseconds(audioActualDurationMilliseconds));
						generalMediaPlayer.seekTo(milisseconds);
						generalMediaPlayer.start();
						if (!theDamnUpdateSeekBarThreadIsRunning)
							updateSeekBar();
					}
					break;
				}
				return false;
			}
		});
		this.generalMediaPlayer.setOnBufferingUpdateListener(this);
		this.generalMediaPlayer.setOnCompletionListener(this);
	}

	public void loadMidi(int anthemNumber) {
		try {
			AssetFileDescriptor afd = getAssets().openFd("anthem_midi_" + String.valueOf(anthemNumber) + ".mid");
			this.generalMediaPlayer.reset();
			this.generalMediaPlayer.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
			this.generalMediaPlayer.prepare();
			this.skBar.setMax(((int) (this.generalMediaPlayer.getDuration()) / 1000) * 1000);
			this.audioDurationMilliseconds = this.generalMediaPlayer.getDuration();
			this.playerTitle.setText(String.valueOf(MyConstants.idAnthemIsPlaying)+ ". "+ MyConstants.titleAnthemIsPlaying);
			this.player.setVisibility(View.VISIBLE);
		} catch (Exception e) {
			Log.e("Error while loading midi file", e.getMessage());
		}
	}

	public void loadSongFromInternet() {
		try {
			this.internetError = InternetConnection.checkConnection(this);
			this.generalMediaPlayer.reset();
			String formatedValue = String.valueOf(MyConstants.idAnthemIsPlaying) + ".mp3";
			if (MyConstants.idAnthemIsPlaying < 10)
				formatedValue = "00" + String.valueOf(MyConstants.idAnthemIsPlaying) + ".mp3";
			else if (MyConstants.idAnthemIsPlaying > 9 && MyConstants.idAnthemIsPlaying < 100)
				formatedValue = "0" + String.valueOf(MyConstants.idAnthemIsPlaying) + ".mp3";
			this.generalMediaPlayer.setDataSource(MyConstants.AUDIOSTREAMINGSERVER + formatedValue);
			this.generalMediaPlayer.prepare();
		} catch (Exception e) {
			Log.e("Error while loading mp3 file", e.getMessage());
		}
	}

	public void loadSongFromInternetCallback() {
		if (this.internetError != 0)
			this.raiseInternetError();
		else {
			this.player.setVisibility(View.VISIBLE);
			this.playerTitle.setText(String.valueOf(MyConstants.idAnthemIsPlaying) + ". " + MyConstants.titleAnthemIsPlaying);
			int milliseconds = this.generalMediaPlayer.getDuration();
			this.skBar.setMax(((int) (milliseconds) / 1000) * 1000);
			this.audioDurationMilliseconds = milliseconds;
			this.audioActualDurationMilliseconds = 0;
			this.audioDuration.setText(Utils.formatMiliseconds(this.audioDurationMilliseconds));
			this.audioActualDuration.setText("00:00");
			this.playerPlayPause();
		}
	}

	public void playerPlayPause() {
		if (!this.generalMediaPlayer.isPlaying()) {
			this.generalMediaPlayer.start();
			this.imgPlayPayse.setImageResource(R.drawable.player_pause);
		} else {
			this.generalMediaPlayer.pause();
			this.imgPlayPayse.setImageResource(R.drawable.player_play);
		}
		if (!this.theDamnUpdateSeekBarThreadIsRunning)
			this.updateSeekBar();
	}

	public void updateSeekBar() {
		if (this.generalMediaPlayer == null) {
			this.theDamnUpdateSeekBarThreadIsRunning = false;
			return;
		}
		this.theDamnUpdateSeekBarThreadIsRunning = true;
		this.skBar.setProgress(this.generalMediaPlayer.getCurrentPosition());
		this.audioActualDuration.setText(Utils.formatMiliseconds(this.audioActualDurationMilliseconds));
		this.audioActualDurationMilliseconds += 1000;
		if (this.generalMediaPlayer.isPlaying()) {
			Runnable r = new Runnable() {
				public void run() {
					updateSeekBar();
				}
			};
			handler.postDelayed(r, 1000);
		} else
			this.theDamnUpdateSeekBarThreadIsRunning = false;
	}

	public void playerStop() {
		this.generalMediaPlayer.stop();
		this.imgPlayPayse.setImageResource(R.drawable.player_play);
		this.player.setVisibility(View.GONE);
	}

	public void updateData() {
		if (DataCache.anthemsCache == null || !this.edtSearch.getText().toString().equals("") || this.forceSearch) {
			this.forceSearch = false;
			this.arrayAnthems = this.dao.fetch(this.edtSearch.getText().toString());
			DataCache.anthemsCache = this.arrayAnthems;
		} else
			this.arrayAnthems = DataCache.anthemsCache;
	}

	public void updateListView() {
		this.lvAnthemsAdapter = new AnthemsAdapter(this, this.arrayAnthems);
		this.lvAnthems.setAdapter(this.lvAnthemsAdapter);
	}

	@Override
	public void onCreateContextMenu(ContextMenu menu, View v,
			ContextMenuInfo menuInfo) {
		if (v.getId() == R.id.lvAnthems) {
			AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) menuInfo;
			AnthemVO obj = (AnthemVO) DataCache.anthemsCache.get(info.position);
			MyConstants.idAnthemIsPlaying = obj.getIdAnthem();
			MyConstants.titleAnthemIsPlaying = obj.getTitle();
			menu.setHeaderTitle(obj.getTitle());
			menu.add(Menu.NONE, 0, 0, R.string.contextMenuMIDI);
			menu.add(Menu.NONE, 1, 1, R.string.contextMenuSong);
		}
	}

	@Override
	public boolean onContextItemSelected(MenuItem item) {
		int menuItemIndex = item.getItemId();
		switch (menuItemIndex) {
		case 0:
//			Animation shake = AnimationUtils.loadAnimation(this, R.anim.shake);
//	        findViewById(R.id.playerSeekBar).startAnimation(shake);
			this.player.setVisibility(View.VISIBLE);
			this.loadMidi(MyConstants.idAnthemIsPlaying);
			this.audioActualDurationMilliseconds = 0;
			this.audioActualDuration.setText("00:00");
			this.audioDuration.setText(Utils.formatMiliseconds(this.audioDurationMilliseconds));
			this.playerPlayPause();
			break;
		case 1:
			CustomWaitDialog cmd = new CustomWaitDialog(this,"loadSongFromInternet", "loadSongFromInternetCallback", true);
			cmd.execute();
			break;
		}
		return true;
	}

	@Override
	public boolean onTouchEvent(MotionEvent me) {
		return gestureScanner.onTouchEvent(me);
	}

	public boolean onDown(MotionEvent e) {
		// TODO Auto-generated method stub
		return false;
	}

	public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
			float velocityY) {
		if (Math.abs(velocityX) > Math.abs(velocityY)) {
			int ini;
			int end;
			Class obj = TextContentPageActivity.class;
			finish();
			if (velocityX < 0) {
				Intent intent = new Intent(FirstPageActivity.this,
						TextContentPageActivity.class);
				intent.putExtra("IDANTHEM", 1);
				startActivity(intent);
				overridePendingTransition(R.anim.push_left_in,
						R.anim.push_left_out);
			} else {
				Intent intent = new Intent(FirstPageActivity.this,
						TextContentPageActivity.class);
				intent.putExtra("IDANTHEM", 640);
				startActivity(intent);
				overridePendingTransition(R.anim.push_right_in,
						R.anim.push_right_out);
			}
		}
		return true;
	}

	public void onLongPress(MotionEvent e) {

	}

	public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX,
			float distanceY) {
		// TODO Auto-generated method stub
		return false;
	}

	public void onShowPress(MotionEvent e) {
		// TODO Auto-generated method stub

	}

	public boolean onSingleTapUp(MotionEvent e) {
		// TODO Auto-generated method stub
		return false;
	}

	public void onBufferingUpdate(MediaPlayer mp, int percent) {
		this.skBar.setSecondaryProgress(percent);
	}

	public void onCompletion(MediaPlayer mp) {
		this.imgPlayPayse.setImageResource(R.drawable.player_play);
		this.audioActualDuration.setText("00:00");
		this.audioActualDurationMilliseconds = 0;
		this.player.setVisibility(View.GONE);
	}
}